from django.shortcuts import render

# Create your views here.
from lkapp.models import LkappModel,LmtModel
from lkapp.serializers import LkappModelSerializer, LkappModelCreateUpdateSerializer,LmtappModelSerializer,LmtappModelCreateUpdateSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from lkapp.lmt import getdara
import asyncio
class LkappDemoModelViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = LkappModel.objects.all()
    serializer_class = LkappModelSerializer
    create_serializer_class = LkappModelCreateUpdateSerializer
    update_serializer_class = LkappModelCreateUpdateSerializer

    filter_fields = ['lk_name', 'server_web_port']
    search_fields = ['lk_name']
class LmtappDemoModelViewSet(CustomModelViewSet):
    """
        list:查询
        create:新增
        update:修改
        retrieve:单例
        destroy:删除
        """
    queryset = LmtModel.objects.all()
    serializer_class = LmtappModelSerializer
    create_serializer_class = LmtappModelCreateUpdateSerializer
    update_serializer_class = LmtappModelCreateUpdateSerializer

    filter_fields = ['lmt_username']
    search_fields = ['lmt_username']

    def LMTstatus(self, request):
        lmtStatus = []
        try:
            data = LkappModel.objects.values('lmt_username','lmt_password') # get返回流媒体账号、密码
            for i in data:
                lmt_username = i['lmt_username']
                lmt_password = i['lmt_password']
                try:
                    lmt = asyncio.run(getdara(lmt_username, lmt_password))
                    kqLmt = LmtModel(lmt_username=lmt_username, sxtzs=lmt[0], sxtqys=lmt[1], sxtzx=lmt[2])
                    lmtStatus.append(kqLmt)
                    # LmtModel.objects.update_or_create(lmt_username=lmt_username,defaults=kqLmt)

                except:
                    print("账号密码错误")
            LmtModel.objects.bulk_create(lmtStatus)
        except LkappModel.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = LkappModelSerializer(instance=lmt_username)
        return Response(serializer.data)

    
